//
//  ZJWatchViewController.swift
//  mini
//
//  Created by Mac on 2017/5/19.
//  Copyright © 2017年 Mac. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZJWatchViewController: UIViewController {
    
    var isOpen:Bool = false
    
    var barItem:UIBarButtonItem?
    
    var tableView:UITableView?
    
    var progressView :ZJProgressView?
    
    var deviceArr:NSArray = NSArray()
    
    var WatchClouser:((_ isConnectWatch:Bool)->())?
    
    var timer:Timer?
    
    var bluetoothImgeButton:UIButton = {

        let btn = UIButton(frame: CGRect(x: ScreenWidth-100, y: 330-50, width: 100, height: 50))
            
        btn.titleLabel?.font  = UIFont.systemFont(ofSize: 16)
        
        btn.setTitle(" 未连接", for: .normal)

        btn.setImage(#imageLiteral(resourceName: "bluetooth_off"), for: .normal)
        
        btn.setTitleColor(.lightGray, for: .normal)
        
        btn.backgroundColor = .white

        return btn
    }()
    
    var blueUnit:BleUtils = {
        
        return BleUtils.getInstance()
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "手环"
        let blueUnit = BleUtils.getInstance()
        
        blueUnit?.getPhooneBleUtilsState({ (s) in
            
            self.isOpen = s==0 ? false :true
            
            if Thread.isMainThread {
                
                self.upDateButtonStatus()
                
            }else{
                
                DispatchQueue.main.async(execute: {
                   
                    self.upDateButtonStatus()
                    
                })
            }
            
            self.isOpen==true ?  self.startScan(): ()
                
            
            
            
        })
        addBackButton()
        setupUI() 
        
        // Do any additional setup after loading the view.
    }
    
    
    func setupUI()  {
        

        if (ZJDevice.sharedInstance().bracelet?.isEmpty)! {
            
            barItem = UIBarButtonItem(title:"解绑" , style: .plain, target: self, action: #selector(disBindWatchClick))
            
        }else{
            
             barItem = UIBarButtonItem(title:"绑定" , style: .plain, target: self, action: #selector(selectBlueTooth))
            
        }
        
        navigationItem.rightBarButtonItem = barItem
        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight-90))
        
        tableView?.delegate = self
        
        tableView?.dataSource = self
        
        tableView?.backgroundColor = .white
        
        tableView?.separatorStyle = .none
        
        tableView?.showsVerticalScrollIndicator = false
       
        tableView?.showsHorizontalScrollIndicator = false
        
        tableView?.estimatedRowHeight = 200
        
        tableView?.rowHeight = UITableViewAutomaticDimension
        
        tableView?.tableFooterView = UIView()
    
        view.addSubview(tableView!)
        
        progressView = ZJProgressView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 330))

        tableView?.tableHeaderView = progressView
        
        progressView?.addSubview(bluetoothImgeButton)

        
    }
    
    @objc func disBindWatchClick()  {
        
         progressView?._rate += 2
        
    }
    
    func selectBlueTooth()  {
        
        
    }
    
    
    func upDateButtonStatus() {
        
        if isOpen {
            
            progressView?.startAnimation()
            
        }else{
            
            progressView?.stopAnimation()
        }
        
    }
    
    
    func startScan()  {
        
        blueUnit.stopScanningDevice()
        
        blueUnit.starScanningDevice { (peripheral, mac, rssi) in
            
            if (peripheral?.name?.hasPrefix("Remote Band 1") == false)
            {return}
            
   
            if let dict:NSDictionary = ZJDevice.sharedInstance().didAndUdid,let bracelet:String = ZJDevice.sharedInstance().bracelet,let uuid:String = dict.object(forKey: bracelet )as? String {
                
                if uuid == peripheral?.identifier.uuidString {
                   
                    let dic = NSMutableDictionary()
                    dic.setObject(peripheral ?? "", forKey: "peripheral" as NSCopying)
                    
                    if ZJDevice.sharedInstance().isConnect == false {
                        
                        self.connectDevice(deviceDict: dic)
                        
                    }
                    
                    return
                }

                
            }else{
                
                let dic = NSMutableDictionary()
                 dic.setObject(peripheral ?? "", forKey: "peripheral" as NSCopying)
                let mstring = NSMutableString(string:mac!)
                
                var macStr = mac
                
                if mac?.isEmpty == false {
                    
                    macStr = mstring.replacingOccurrences(of: ":", with: "")
                    
                    macStr = macStr?.lowercased()
    

                }
                
                dic.setObject(macStr ?? "", forKey: "macAddress" as NSCopying)
                dic.setObject(rssi ?? "", forKey: "rssi" as NSCopying)
                dic.setObject(peripheral!.name ?? "", forKey: "name" as NSCopying)
                dic.setObject(ZJDevice.sharedInstance().bracelet ?? "", forKey: "bracelet" as NSCopying)
                self.deviceArr.adding(dic)

                if let macstr = macStr,let braceletstr = ZJDevice.sharedInstance().bracelet {
                    
                    if macstr.caseInsensitiveCompare(braceletstr) == .orderedSame{
                        
                        if ZJDevice.sharedInstance().isConnect == false {
                            
                            self.connectDevice(deviceDict: dic)
                            
                        }
                    }
                    
                }
                //只要是搜索到的设备进行了更新，就对绑定界面界面进行刷新
                
                
            }
            
            
        }
        
        
    }
    
    func connectDevice(deviceDict:NSMutableDictionary)  {
        
        blueUnit.stopScanningDevice()
        let per: CBPeripheral = deviceDict.object(forKey: "peripheral") as! CBPeripheral
        blueUnit.connectDevice(per, timeout: 10) { (state) in
            
            ZJDevice.sharedInstance().isConnect = state>0 ? true:false
            
            self.connectDeviceBlock(state: Int(state), per: per)
            
            return
        }
    }
    
    
    func connectDeviceBlock(state:Int,per:CBPeripheral)  {
        
        if  (WatchClouser != nil) {
            WatchClouser!(ZJDevice.sharedInstance().isConnect)
        }
        
        if Thread.isMainThread {
            
            updataBlueTooth(state:state,per: per)
            
        }else{
            
            DispatchQueue.main.async(execute: {
                
              self.updataBlueTooth(state:state,per: per)
                
            })
        }
        
        
    }
    
    func updataBlueTooth(state:Int,per:CBPeripheral) {
        
        //连接成功
        if state>0 {
            
            syncSevenWatchData()
            
            let dict:NSMutableDictionary = NSMutableDictionary()
            
            dict[ZJDevice.sharedInstance().bracelet ?? ""] = per.identifier.uuidString
            
            ZJDevice.sharedInstance().didAndUdid = dict
            
            bluetoothImgeButton.setTitle(" 已连接", for: .normal)
            
            bluetoothImgeButton.setImage(#imageLiteral(resourceName: "bluetooth_on"), for: .normal)
            
            bluetoothImgeButton.setTitleColor(kWatchColor, for: .normal)

            
            
        }else{
            
            stopLink()
            
            bluetoothImgeButton.setTitle(" 未连接", for: .normal)
            
            bluetoothImgeButton.setImage(#imageLiteral(resourceName: "bluetooth_off"), for: .normal)
            
            bluetoothImgeButton.setTitleColor(.lightGray, for: .normal)
            
            showSVProgress(isShow: false)
            
        }
        
    }
    
    //加载手环数据
    func syncSevenWatchData()  {
        
        
    }
    
    func showSVProgress(isShow:Bool)  {
        
        if (isShow) {
            SVProgressHUD.setDefaultStyle(.light)
            SVProgressHUD.setDefaultMaskType(.custom)
            SVProgressHUD.show(withStatus: "手环数据获取中")
            UIApplication.shared.keyWindow?.isUserInteractionEnabled = false
           
        }else{
            SVProgressHUD.dismiss()
             UIApplication.shared.keyWindow?.isUserInteractionEnabled = true
        }
    }
    
    func stopLink()  {
        
        if ZJDevice.sharedInstance().cotimer == nil {return}
        
       ZJDevice.sharedInstance().cotimer?.invalidate()
        
       ZJDevice.sharedInstance().cotimer = nil
        
    }
    
    func addBackButton() {
        
        let btn:ZJNavButton = ZJNavButton(frame: CGRect(x: 0, y: 0, width: 19, height: 19))
        
        btn.setImage(#imageLiteral(resourceName: "back"), for: .normal)
        
        btn.addTarget(self, action: #selector(back), for: .touchUpInside)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
        
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
        stopLink()
        
        timer?.invalidate()
        
        timer = nil
        
    }
    
    @objc func back()  {
        dismiss(animated: true, completion: nil);
    }
    
    func backClick()  {
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  

}

extension ZJWatchViewController : UITableViewDelegate,UITableViewDataSource {
    @available(iOS 2.0, *)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
      
        let cell:ZJWatchCell? = ZJWatchCell.typeViewWithTableView(tableView: tableView)
        
//        cell.title = self.typeTitleArray[indexPath.row];
        
//        if (firstRunModel==nil) {
//            
//            cell.content = "0步";
//            
////            cell.time = [NSDate getNowDateStr];
//            
//            return cell;
//        }
//        
        if (indexPath.row==0) {
            
            cell?.title = "健康数据"
            
            cell?.content = "0步"
            
            cell?.time = "2017-05-22";
            
        }else{
            
            
        }
        
        return cell!;
    }
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row==0{
            
            let watchVc:ZJWacthDetailViewController = ZJWacthDetailViewController()
            
            navigationController?.pushViewController(watchVc, animated: true)
            
        }else{
            
        }
        
    }

    

    
}




